<?php

namespace app\api\controller;

use addons\epay\library\Service;
use app\admin\model\BillModel;
use app\admin\model\DiyPushModel;
use app\admin\model\HouseModel;
use app\admin\model\RoomBoardLogModel;
use app\admin\model\SmsRechargeLogModel;
use app\admin\model\UserRechargeModel;
use app\common\controller\Api;
use app\common\library\Wechat;
use app\common\model\Message;
use app\common\model\OrderPaymentRecords;
use app\common\model\PaymentRecords;
use think\Db;
use think\Exception;


class Notify extends Api
{
    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';


    public function pay_success()
    {
        $paytype = 'wechat';
        $pay = Service::checkNotify($paytype);
        if (!$pay) {
            return json(['code' => 'FAIL', 'message' => '失败'], 500, ['Content-Type' => 'application/json']);
        }

        // 获取回调数据，V3和V2的回调接收不同
        $data = Service::isVersionV3() ? $pay->callback() : $pay->verify();


        Db::startTrans();
        try {
            //微信支付V3返回和V2不同
            if (Service::isVersionV3() && $paytype === 'wechat') {
                $data = $data['resource']['ciphertext'];
                $data['total_fee'] = $data['amount']['total'];
            }

            \think\Log::record('微信支付回调');
            \think\Log::record($data);
            //获取支付金额、订单号
            $payamount = $paytype == 'alipay' ? $data['total_amount'] : $data['total_fee'] / 100;
            $out_trade_no = $data['out_trade_no'];
            $transaction_id = $data['transaction_id'];

            \think\Log::record("回调成功，订单号：{$out_trade_no}，金额：{$payamount}");

            $recharge = UserRechargeModel::get(['order_no' => $out_trade_no]);
            if (!$recharge) {
                throw new Exception('订单号不存在');
            }
            if ($recharge->status == 0) {
                $recharge->status = 1;
                $recharge->transaction_id = $transaction_id;
                $recharge->save();

                \app\common\model\User::score($recharge->score, $recharge->user_id, '充值', 7);

                /*\app\common\model\User::update([
                    'level' => $recharge->level_id,
                ], [
                    'id' => $recharge->user_id
                ]);*/
            }

            Db::commit();
        } catch (\Throwable $e) {
            Db::rollback();
            \think\Log::record("回调逻辑处理错误:" . $e->getMessage(), "error");
            return json(['code' => 'FAIL', 'message' => '失败'], 500, ['Content-Type' => 'application/json']);
        }

        //下面这句必须要执行,且在此之前不能有任何输出
        if (Service::isVersionV3()) {
            return $pay->success()->getBody()->getContents();
        } else {
            return $pay->success()->send();
        }
    }


    public function sms_pay_success()
    {
        $paytype = 'wechat';
        $pay = Service::checkNotify($paytype);
        if (!$pay) {
            return json(['code' => 'FAIL', 'message' => '失败'], 500, ['Content-Type' => 'application/json']);
        }

        // 获取回调数据，V3和V2的回调接收不同
        $data = Service::isVersionV3() ? $pay->callback() : $pay->verify();


        Db::startTrans();
        try {
            //微信支付V3返回和V2不同
            if (Service::isVersionV3() && $paytype === 'wechat') {
                $data = $data['resource']['ciphertext'];
                $data['total_fee'] = $data['amount']['total'];
            }

            //获取支付金额、订单号
            $payamount = $paytype == 'alipay' ? $data['total_amount'] : $data['total_fee'] / 100;
            $out_trade_no = $data['out_trade_no'];
            $transaction_id = $data['transaction_id'];

            $recharge = SmsRechargeLogModel::get(['order_no' => $out_trade_no]);
            if (!$recharge) {
                throw new Exception('订单号不存在');
            }
            if ($recharge->status == 0) {
                $recharge->status = 1;
                $recharge->transaction_id = $transaction_id;
                $recharge->save();
            }

            Db::commit();
        } catch (\Throwable $e) {
            Db::rollback();
            \think\Log::record("短信充值回调逻辑处理错误:" . $e->getMessage(), "error");
            return json(['code' => 'FAIL', 'message' => '失败'], 500, ['Content-Type' => 'application/json']);
        }

        //下面这句必须要执行,且在此之前不能有任何输出
        if (Service::isVersionV3()) {
            return $pay->success()->getBody()->getContents();
        } else {
            return $pay->success()->send();
        }
    }

    public function push()
    {
        $list = DiyPushModel::where('status', 0)->select();
        $count = 0;
        foreach ($list as $item) {
            $openid = \app\admin\model\User::where('id', $item['user_id'])->value('openid', 0);
            if (empty($openid)) {
                $item->status = 2;
                $item->save();
                continue;
            }

            $where = [];
            $where['status'] = 1;
            $where['is_finish'] = 0;
            $where['community'] = $item['community'];
            $where['rent'] = ['>=', $item['min_rent']];
            if ($item['max_rent']) {
                $where['rent'] = ['<=', $item['max_rent']];
            }
            $where['floor'] = ['>=', $item['min_floor']];
            if ($item['max_floor']) {
                $where['floor'] = ['<=', $item['max_floor']];
            }
            if ($item['house_type']) {
                $where['house_type'] = $item['house_type'];
            }
            if ($item['payment_type']) {
                $where['payment_type'] = $item['payment_type'];
            }

            if ($item['tags']) {
                $tags = explode(',', $item['tags']);
                foreach ($tags as $tag) {
                    $where[] = Db::raw('find_in_set(' . $tag . ',tags)');
                }
            }
            $house = HouseModel::where($where)->find();

            if ($house) {
                $template_id = 'eo7D0M0GhE6hhQciisiJAtzJ8z2QRSrhKnUYfOk9C8k';
                $data = [
                    'thing2' => ['value' => '为您匹配到心仪的房源，请及时查看。'],
                    'time1' => ['value' => date('Y-m-d H:i:s')],
                ];
                $page = '';
                //跳转小程序类型：developer为开发版；trial为体验版；formal为正式版；默认为正式版
                $state = 'trial';
                $res = (new Wechat())->sendMessage($item['id'], $openid, $template_id, $data, $page, $state);
                if ($res) {
                    $item->status = 1;
                } else {
                    $item->status = 2;
                }
                $item->house_id = $house['id'];
                $item->save();
                $count += 1;
            }

        }

        return sprintf('查询到%s条待推送数据，满足条件推送%s条', count($list), $count);
    }


    public function pay_fees()
    {
        $paytype = 'wechat';
        $pay = Service::checkNotify($paytype);
        if (!$pay) {
            return json(['code' => 'FAIL', 'message' => '失败'], 500, ['Content-Type' => 'application/json']);
        }

        // 获取回调数据，V3和V2的回调接收不同
        $data = Service::isVersionV3() ? $pay->callback() : $pay->verify();


        Db::startTrans();
        try {
            //微信支付V3返回和V2不同
            if (Service::isVersionV3() && $paytype === 'wechat') {
                $data = $data['resource']['ciphertext'];
                $data['total_fee'] = $data['amount']['total'];
            }

            \think\Log::record('微信支付回调');
            \think\Log::record($data);
            //获取支付金额、订单号
            $payamount = $paytype == 'alipay' ? $data['total_amount'] : $data['total_fee'] / 100;
            $out_trade_no = $data['out_trade_no'];
            $transaction_id = $data['transaction_id'];

            \think\Log::record("回调成功，订单号：{$out_trade_no}，金额：{$payamount}");


            $info = OrderPaymentRecords::get(['pay_sn' => $out_trade_no]);
            if (!$info) {
                return json(['code' => 'FAIL', 'message' => '订单号不存在'], 500, ['Content-Type' => 'application/json']);
            }
            if ($info->status == 0) {
                $info->status = 1;
                $info->pay_type = 1;
                $info->updatetime = time();
                $info->save();
                $paymentRecords = PaymentRecords::get($info->other_id);
                if (empty($paymentRecords)) {
                    throw new Exception('缴费记录不存在');
                }
                $paymentRecords->status = 1;
                $paymentRecords->save();


                if ($paymentRecords->relation_id) {
                    BillModel::update(['status' => 2], ['id' => $paymentRecords->relation_id]);
                }


                $message_data = [
                    'type' => Message::TYPE_FORE,
                    'user_id' => $info->homeowner_id,
                    'title' => '用户已缴费标题',
                    'content' => '用户已缴费内容',
                ];
                $message_data['other_id'] = $info->id;
                Message::add($message_data);
            }

            Db::commit();
        } catch (\Throwable $e) {
            Db::rollback();
            \think\Log::record("回调逻辑处理错误:" . $e->getMessage(), "error");
            return json(['code' => 'FAIL', 'message' => '失败'], 500, ['Content-Type' => 'application/json']);
        }

        //下面这句必须要执行,且在此之前不能有任何输出
        if (Service::isVersionV3()) {
            return $pay->success()->getBody()->getContents();
        } else {
            return $pay->success()->send();
        }
    }
}
